#pragma once

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

const std::string pathname = "/home/dck/os/process/processCommunicate/";
const int proj_id = 0x11223344;
const std::string filename = "fifo";

const int size = 4096; //建议申请4096的整数倍,因为系统实际开辟的就是4096的整数倍!

key_t GetKey()
{
    key_t key = ftok(pathname.c_str(), proj_id);
    if(key < 0)
    {
        std::cerr << "errno: " << errno << ", errstring" << strerror(errno) << std::endl;
        exit(1);
    }
    return key;
}

std::string ToHex(int id)
{
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "0x%x", id);
    return buffer;
}

int CreateshmHelper(key_t key, int flag)
{
    int shmid = shmget(key, size, flag); //共享内存也是有权限的!
    if(shmid < 0)
    {
        std::cerr << "errno: " << errno << ", errstring" << strerror(errno) << std::endl;
        exit(2);
    }
    return shmid;
}

int Createshm(key_t key)
{
    return CreateshmHelper(key, IPC_CREAT | IPC_EXCL | 0664);
}

int GetShm(key_t key)
{
    return CreateshmHelper(key,  IPC_CREAT/*0也可以*/);
}


bool MakeFifo()
{
    int n = mkfifo(filename.c_str(), 0666);
    if(n < 0)
    {
        std::cerr << "errno: " << errno << ", errstring" << strerror(errno) << std::endl;
        return false;
    }
    std::cout << "mkfifo success...read" << std::endl;
    return true;
}

